<?php

namespace system\core;

class regex
{

	static $counter;
	static $makeitoptional;

	static function oo()
	{
		self::$makeitoptional = true;
		$string = self::o(func_get_args());
		self::$makeitoptional = false;
		return $string;
	}

	static function t($arr)
	{
//		print_r($arr);
		foreach( $arr as $data )
		{
			if( is_array($data) )
			{
				$list[] = self::oo($data);
			}
			else
			{
				$list[] = $data;
			}
		}
		$list = self::array_clean($list);
		return implode(' ?', $list);
	}

	static function o()
	{
		if( !func_get_args() ) return "";
		$arguments = func_get_args();
		foreach( $arguments as $data )
		{
			if( is_array($data) )
			{
				foreach( $data as $sub )
					$list[] = self::o($sub);
			}
			else
			{
				$list[] = $data;
			}
		}

		$list = self::array_clean($list);
		if( count($list) > 1 )
		{
			return '(?:'.implode('|', $list).')'.(self::$makeitoptional ? "?" : "");
		}
		elseif( count($list) == 1 )
		{
			return implode('|', $list);
		}
		else
		{
			return "";
		}
	}

	static function sortbylen(&$array, $direction = SORT_ASC)
	{
		foreach( $array as $key => $val )
		{
			$lenref[] = strlen($val);
		}
		array_multisort($lenref, $direction, SORT_NUMERIC, $array);
	}

	static function q($string)
	{
		return preg_quote($string);
	}

	static function enumerate_storages($string, $remove_named_storages=false)
	{
		if( $remove_named_storages )
		{
			preg_match_all("/\?\<((?!\>)[a-z]*)\>/i", $string, $match, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
		}
		else
		{
			preg_match_all("/\<((?!\>)[a-z]*)\>/i", $string, $match, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
		}
//		print_r($match);
		foreach( $match as $token )
		{
			$items[$token[1][0]]++;
		}

		krsort($match);
		foreach( $match as $token )
		{
			$itemNumber = "_".(--$items[$token[1][0]]);
			if( $remove_named_storages )
			{
				$string = substr_replace($string, "", $token[0][1], strlen($token[0][0]));
			}
			else
			{
				$string = substr_replace($string, "<".$token[1][0].$itemNumber.">", $token[0][1], strlen($token[0][0]));
			}
		}
		return $string;
	}

	static function c()
	{
		self::$counter++;
		return self::$counter;
	}

	static function array_clean($arr)
	{
		if( $arr ) foreach( $arr as $key => $val )
			{
				if( $val !== "" )
				{
					$ret[$key] = $val;
				}
			}
		return $ret;
	}

	static function strip_offsets($array)
	{
		foreach( $array as $key => $val )
		{
			$cleanarray[$key] = $val[0];
		}
		return $cleanarray;
	}

}

?>
